package search;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 *
 * @author Golden-Tech
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
       Main main = new Main();
       String result = main.googleSearchEngine("barcelona");

       PrintWriter pw = new PrintWriter("google_search_engine_result.txt");
       pw.print(result);
       //save in the file
     
    }

    public String googleSearchEngine(String query) throws Exception {

        String key = "AIzaSyC5dkyoX8dX7PsWpaUoGMUD2eP_D1w4uGo";
        String qry = query;
        String result = "";
        String cx = "013875942894455285041:uqxv-ejckau";
        URL url = new URL(
                "https://www.googleapis.com/customsearch/v1?key" + key + "&cx=" + cx + "&q=" + qry + "&alt=json");


        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  
        conn.setRequestMethod("GET");
   
        conn.setRequestProperty("Accept", "application/json");
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
     
        String output;
        System.out.println("Output from Server .... \n");
        int count = 0;
        while ((output = br.readLine()) != null) {

            if (output.contains("\"link\": \"") && count < 10) {
                String link = output.substring(output.indexOf("\"link\": \"") + ("\"link\": \"").length(), output.indexOf("\","));
                //System.out.println(link); //Will print the google search links
//        try{
//        OutputStream out = new FileOutputStream("google_search_engine_result.txt");
//        InputStream in = url.openStream();
//        DTD html = DTD.getDTD("html");
//        System.out.println(html.getName());
//        in.close();
//        out.flush();
//        out.close();
//        }catch (Exception ex){ System.err.println("Usage: java PageSaver url local_file"); }
                result += link;
            }
            count ++;
        }

        conn.disconnect();
        return result;
    }
}
